from rest_framework import serializers
from .models import *
RE_MOBILE = '^1[35789]\d{9}$'
from datetime import datetime, timedelta
import re
from rest_framework.validators import UniqueValidator

class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self, mobile):
        if UserProfile.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError("手机号已注册")
        if not re.match(RE_MOBILE, mobile):
            raise serializers.ValidationError("手机号格式不正确")
        one_minutes_ago = datetime.now() - timedelta(hours=0,minutes=1,seconds=0)
        if VerifyCode.objects.filter(mobile=mobile,add_time__gt=one_minutes_ago):
            raise serializers.ValidationError("距离上一次发送未超过60秒")
        return mobile


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('name', 'birthday', 'gender', 'mobile', 'email')




class UserRegisterSerializer(serializers.ModelSerializer):
    username = serializers.CharField(label='用户名',required=True,allow_blank=False,validators=[UniqueValidator(UserProfile.objects.all())])
    code = serializers.CharField(label='验证码',required=True,write_only=True,max_length=4,min_length=4)
    password = serializers.CharField(label='密码',write_only=True,style={"input_type":"password"})

    def validate_code(self, code):
        records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time')
        if records:
            record = records[0]
            five_ago = datetime.now()-timedelta(hours=0,minutes=5,seconds=0)
            if record.add_time < five_ago:
                raise serializers.ValidationError("验证码超时")
            if record.code != code:
                raise serializers.ValidationError("验证码错误")
        else:
            raise serializers.ValidationError("手机号未收到任何信息")

    def create(self, validated_data):
        user = super().create(validated_data=validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

    def validate(self, attrs):
        del attrs['code']
        return attrs
    class Meta:
        model = UserProfile
        fields = ('username', 'code', 'password')